﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AgileZen.Models;

namespace AgileZen.Sample.Controllers
{
    public class PhaseController : AgileZenController
    {
        //
        // GET: /Phases/

        public ActionResult Index(int projectId)
        {
            var phases = AgileZenService.GetPhases(projectId);
            return View(phases);
        }

        public ActionResult Details(int id, int projectid)
        {
            var phase = AgileZenService.GetPhase(projectid, id);

            return View(phase);
        }

        public ActionResult Add(int projectid)
        {
            return View();
        }

        [HttpPost]
        public ActionResult Add(int projectid, Phase phase)
        {
            try
            {
                AgileZenService.CreatePhase(projectid, ref phase);

                return RedirectToAction("Details", new { id = phase.Id, projectid = projectid });
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Edit(int projectid, int id)
        {

            try
            {
                var phase = AgileZenService.GetPhase(projectid, id);
                return View(phase);
            }
            catch
            {
                return View();
            }

        }

        //
        // POST: /Project/Edit/5

        [HttpPost]
        public ActionResult Edit(int projectid, int id, Phase phase)
        {
            try
            {
                // TODO: Add update logic here
                AgileZenService.UpdatePhase(projectid, ref phase);
                return RedirectToAction("Index", new { projectid = projectid });
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Reorder(int id)
        {
            try
            {
                //var 
                var phases = AgileZenService.GetPhases(id);
                var order = new List<int>(phases.CurrentOrder);

                var second = order.ElementAt(1);
                var third = order.ElementAt(2);

                order[1] = third;
                order[2] = second;

                phases = AgileZenService.ReorderPhases(id, order.ToArray());
                return RedirectToAction("Index", new { projectid = id });
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Delete(int projectid, int id)
        {
            try
            {
                AgileZenService.DeletePhase(projectid, id);

                return RedirectToAction("Index", new { projectid = projectid });
            }
            catch
            {
                return View();
            }
        }

    }
}
